package com.wyzc.exam.dao;

import java.io.*;
import java.util.*;

import com.wyzc.exam.entity.Question;
import com.wyzc.exam.entity.User;
import com.wyzc.exam.util.IOUtil;
import com.wyzc.exam.util.ReadUtil;

public class EntityContext {
	private HashMap<String, User> users = new HashMap<String, User>();
    private HashMap<Integer, ArrayList<Question>> questions  = new HashMap<Integer, ArrayList<Question>>();
	public EntityContext() {
		try {
			loadUser();
			loadQuestion();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void loadQuestion() throws IOException{
		BufferedReader br = IOUtil.getReader(ReadUtil.getMessage("questionpath"));
		 String questionmessage = null;
		 while((questionmessage = br.readLine()) != null) {
			Question question = parseQuestion(br, questionmessage);
			putQuestion(question);
		 }
	}

	private void putQuestion(Question question) {
		int level = question.getLevel();
		if(questions.containsKey(level)) {
			questions.get(level).add(question);
		}else{
			ArrayList<Question> levelQuestions = new ArrayList<Question>();
			levelQuestions.add(question);
			questions.put(level, levelQuestions);
		}
		
	}

	public Question parseQuestion(BufferedReader br, String questionmessage)
			throws IOException {
		String regex = "[@,][a-z]+=";
		Question question = new Question();
		String[] ss = questionmessage.split(regex);
		question.setScore(Integer.parseInt(ss[2]));
		question.setLevel(Integer.parseInt(ss[3]));
		question.setAnswers(getAnswers(ss[1]));
		String title = br.readLine();
		question.setTitle(title);
		question.setOptions(getOption(br));
		return question;
	}
	private ArrayList<String> getOption(BufferedReader br) throws IOException {
		ArrayList<String > options = new ArrayList<String>();
		options.add(br.readLine());
		options.add(br.readLine());
		options.add(br.readLine());
		options.add(br.readLine());
	    return options;
	}
    private ArrayList<Integer> getAnswers(String ans) {
    	String [] answers = ans.split("/");
    	ArrayList<Integer > as = new ArrayList<Integer>();
    	for(String answer: answers) {
    		as.add(Integer.parseInt(answer));
    	}
    	return as;
    }
    
	private void loadUser() throws IOException {
		BufferedReader br = IOUtil.getReader(ReadUtil.getMessage("userpath"));
		String str = null;
		while ((str = br.readLine()) != null) {
			if (str.charAt(0) == '#')
				continue;
			String[] userMessage = str.split(":");
			User user = new User(userMessage[0], userMessage[1],
					userMessage[2], userMessage[3]);
			users.put(user.getId(), user);
		}
	  IOUtil.close();
	}
    public HashMap<Integer, ArrayList<Question>> getQuestions() {
		return questions;
	}
	public HashMap<String, User> getUsers() {
		return users;
	}
}
